//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System.ComponentModel;
using System.IO;
using System.Workflow.ComponentModel;

namespace Microsoft.Research.ScientificWorkflow.Activities
{
    [Name("Local File Writer", "File Writer")]
    [Description("Writes the contents of a memory stream to a local file")]
    [WorkflowCategory("Data")]
    public partial class FileWriter : System.Workflow.ComponentModel.Activity
    {
        #region Property Definitions
        // Required Input Property
        public static DependencyProperty InputStreamProperty =
            DependencyProperty.Register("InputStream", typeof(Stream), typeof(FileWriter));
        public static DependencyProperty OutputFileProperty =
            DependencyProperty.Register("OutputFile", typeof(string), typeof(FileWriter));

        [RequiredInputParam]
        [Name("Input Stream")]
        [Description("The memory stream to be written to file")]
        public Stream InputStream
        {
            get { return ((Stream)(base.GetValue(FileWriter.InputStreamProperty))); }
            set { base.SetValue(FileWriter.InputStreamProperty, value); }
        }

        [RequiredInputParam]
        [Name("Output File Location", "Output File")]
        [Description("The location of the output file")]
        public string OutputFile
        {
            get { return ((string)(base.GetValue(FileWriter.OutputFileProperty))); }
            set { base.SetValue(FileWriter.OutputFileProperty, value); }
        }
        #endregion

        public FileWriter()
		{
			//InitializeComponent();
		}

        /// <summary>
        /// Opens a stream on the input file 
        /// </summary>
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            if (!string.IsNullOrEmpty(OutputFile))
            {
                try
                {
                    FileInfo fileInfo = new FileInfo(OutputFile);
                    Stream writeStream = fileInfo.OpenWrite();

                    byte[] byteArray = new byte[InputStream.Length];
                    InputStream.Read(byteArray, 0, byteArray.Length);
                    writeStream.Write(byteArray, 0, byteArray.Length);
                }
                catch (IOException)
                {
                    // Do nothing.
                }
            }

            return ActivityExecutionStatus.Closed;
        }
	}
}
